<?php

declare (strict_types=1);

namespace app\admin\service\cloud;

use cores\authorize\Http;
use cores\authorize\Tools;
use cores\authorize\AuthFile;
use cores\exception\BaseException;
use app\common\service\BaseService;

/**
 * 授权信息
 * Class Authorize
 */
class Authorize extends BaseService
{
    /**
     * 获取授权用户信息
     * @return array
     * @throws BaseException
     */
    public function getInfo(): array
    {
        $authFileData = $this->getAuthFile();
        $accountData = $this->getAccount($authFileData);
        return [
            'name' => $authFileData['name'],
            'contact' => $authFileData['contact'],
            'authorizeTime' => $authFileData['authorizeTime'],
            'expirationTime' => $authFileData['expirationTime'],
            'licenseStatus' => $authFileData['status'],
            'userKey' => $authFileData['UserKey'],
            'registerTime' => $accountData['registerTime'],
            'accountStatus' => $accountData['status'],
            'accountDomains' => $accountData['domains'],
            'authStatus' => $authFileData['status'] && $accountData['status'],   // 授权状态
            'message' => $this->getError() ?: '恭喜您，当前已获得合法商业授权，可正常使用本系统，感谢您的支持'
        ];
    }

    /**
     * 读取许可证文件信息
     * @return array
     * @throws BaseException
     */
    private function getAuthFile(): array
    {
        $AuthFile = AuthFile::getInstance();
        $auth = $AuthFile->getAuthFile();
        $authData = $AuthFile->getActivationData($auth);
        try {
            $authData['status'] = $AuthFile->checkAuthFile($auth, $authData);
        } catch (\Exception $e) {
            $authData['status'] = false;
            $this->error = $e->getMessage();
        }
        return $authData;
    }

    /**
     * 获取当前授权的域名列表
     * @param array $authData
     * @return array
     * @throws BaseException
     */
    private function getAccount(array $authData): array
    {
        $Http = new Http();
        $Http->setAppToken($authData['AppID'], $authData['AppSecret']);
        $data = $Http->getAuthDomains();
        return [
            'registerTime' => $data['registerTime'], // 账户注册时间
            'status' => $this->checkDomain($data['domains']), // 账户激活状态
            'domains' => $data['domains'], // 授权域名列表
        ];
    }

    /**
     * 验证当前域名是否存在域名授权列表
     * @param array $authDomains
     * @return bool
     */
    private function checkDomain(array $authDomains): bool
    {
        $currentDomain = Tools::getHost();
        if (!in_array($currentDomain, $authDomains)) {
            $this->error = "很抱歉，检测到当前域名未进行商业授权，系统将无法正常运行；当前域名为：{$currentDomain}";
            return false;
        }
        return true;
    }
}